package com.reone.viewpagerbrowser.view;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;


import com.reone.viewpagerbrowser.R;

import java.util.ArrayList;


/**
 * Created by wangxingsheng on 16/6/20.
 */

public class ViewsPagerBrowser extends FrameLayout {

    private Context mContext;
    private ArrayList<View> views;
    private ViewPager mViewPager;
    private BrowsePagerAdapter mAdapter;
    private LinearLayout mPointContainer;
    private boolean canBecircle;
    private OnBrowserViewPagerItemClickListner mOnBrowserViewPagerItemClickListner;
    private OnPageScrolledListener onPageScrolledListener;
    private OnPageSelectedListener onPageSelectedListener;
    private OnPageScrollStateChangedListener onPageScrollStateChangedListener;
    private ArrayList<View> mPoints = new ArrayList<View>();
    private int firstIndex = 0;

    public ViewsPagerBrowser(Context context) {
        super(context);
        init();
    }

    public ViewsPagerBrowser(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ViewsPagerBrowser(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init(){
        mContext = getContext();
        LayoutInflater.from(mContext).inflate(R.layout.views_pager_browser_layout, this,true);
        mViewPager = (ViewPager) findViewById(R.id.views_pager_browser_viewpager);
        mPointContainer = (LinearLayout) findViewById(R.id.point_container);
        mAdapter = new BrowsePagerAdapter();
    }

    /**
     * 初始化数据
     * @param views
     */
    public void initOrUpdateViews(final ArrayList<View> views){
        this.views = views;
        addPoint();
        if(mViewPager.getAdapter()==null){
            mViewPager.setAdapter(mAdapter);
        }else{
            mViewPager.getAdapter().notifyDataSetChanged();
        }
        if(canBecircle){
            mViewPager.setCurrentItem(views.size()*128);
        }
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if(onPageScrolledListener!=null){
                    onPageScrolledListener.onPageScrolled(position % views.size(),positionOffset,positionOffsetPixels);
                }
            }

            @Override
            public void onPageSelected(int position) {
                changePage(position % views.size());
                if(onPageSelectedListener!=null){
                    onPageSelectedListener.onPageSelected(position % views.size());
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if(onPageScrollStateChangedListener != null){
                    onPageScrollStateChangedListener.onPageScrollStateChanged(state);
                }
            }
        });
    }

    public void setCurrentItem(int pos){
        mViewPager.setCurrentItem(views.size() * 128 + pos);
    }

    /**
     * 设置viewPager是否循环
     * @param bool
     */
    public void setCanBecircle(boolean bool){
        this.canBecircle = bool;
    }

    public void setItemClickListner(OnBrowserViewPagerItemClickListner onBrowserViewPagerItemClickListner){
        this.mOnBrowserViewPagerItemClickListner = onBrowserViewPagerItemClickListner;
    }

    public interface OnBrowserViewPagerItemClickListner{
        void onItemClickListner(View itemview, int pos);
    }
    public void setOnPageScrolledListener(OnPageScrolledListener listener){
        onPageScrolledListener = listener;
    }
    public interface OnPageScrolledListener{
        void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);
    }
    public void setOnPageSelectedListener(OnPageSelectedListener listener){
        onPageSelectedListener = listener;
    }
    public interface OnPageSelectedListener{
        void onPageSelected(int position);
    }
    public void setOnPageScrollStateChangedListener(OnPageScrollStateChangedListener listener){
        onPageScrollStateChangedListener = listener;
    }
    public interface OnPageScrollStateChangedListener{
        void onPageScrollStateChanged(int state);
    }

    class BrowsePagerAdapter extends PagerAdapter {

        /**
         * 获得当前界面数
         */
        @Override
        public int getCount() {
            if (views != null) {
                if(canBecircle){
                    return Integer.MAX_VALUE;
                }else{
                    return views.size();
                }
            } else return 0;
        }

        /**
         * 判断是否由对象生成界面
         */
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (View) arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(container);
        }

        /**
         * 初始化position位置的界面
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            final int index = position % views.size();
            if (container.getChildCount() == views.size()) {
                container.removeView(views.get(index));
            }
            try {
                container.addView(views.get(index), 0);
            }catch (IllegalStateException e){
                container.removeView(views.get(index));
                container.addView(views.get(index), 0);
            }
            if(mOnBrowserViewPagerItemClickListner!=null){
                final View itemview = views.get(index);
                if(itemview!=null){
                    itemview.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mOnBrowserViewPagerItemClickListner.onItemClickListner(itemview,index);
                        }
                    });
                }
            }
            return views.get(index);
        }
    }


    /**
     * 选中页改变时,切换点组的状态
     * @param index
     */
    private void changePage(int index){
        if(mPoints!=null&&mPoints.size()>=views.size()){
            mPoints.get(index).setBackgroundResource(R.drawable.oval_choose);
            for(int i = 0;i<mPoints.size();i++){
                if(i == index)continue;
                else{
                    mPoints.get(i).setBackgroundResource(R.drawable.oval_un_choose);
                }
            }
        }
    }

    /**
     * 添加点组
     */
    private void addPoint(){
        mPointContainer.removeAllViews();
        mPoints.clear();
        //dip 转换成px
        float scale = getResources().getDisplayMetrics().density;
        int size = (int) (5 * scale + 0.5f);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(size,size);
        params.rightMargin = size;
        for (int i=0;i<views.size();i++){
            View point = new View(getContext());
            point.setBackgroundResource(R.drawable.oval_un_choose);
            mPoints.add(point);
            mPointContainer.addView(point,params);
        }
        //设置初始位置
        if(firstIndex!=-1){
            mPoints.get(firstIndex).setBackgroundResource(R.drawable.oval_choose);
        }
    }

}
